package com.fsbm.ctech.maxis.ebpsbackend;

import java.io.*;
import java.text.*;
import java.util.zip.*;
import java.util.Date;
import java.sql.*;

import com.fsbm.ctech.maxis.ebpsbackend.ConfigObject;
import com.fsbm.ctech.maxis.ebpsbackend.PrepareFiles;
import com.fsbm.ctech.maxis.ebpsbackend.DBLog;

/**
 * Zips the data set produced by the different email related components. Uses the
 * Configuration Object for the SMTP required information. Each function can be combined
 * as generic in the future.
 * <p>
 * Maxis Backend Program - Zips the Email related information built locally as a set.
 *
 * @author Michael Ty Chan
 */

public class BuildZipSet {
   static final int BUFFER = 262144;
   static ConfigObject cfgObj = new ConfigObject();
   public static void ZipSet(){
      try {
         // get a list of files from current directory
         File f               = new File(cfgObj.workDirectory);
         String files[]       = f.list();
         DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'X'");

         // these variables are needed to get a unique file name based from the input
         String srchvalue1    = "X", srchvalue2 = ".csv", zipFileTag ="";
         int srchPos1         = 0,   srchPos2 = 0,       zipFileNumber = 0;
         //create a unique file name based from the input filename of the csv file
         for (int i=0; i<files.length; i++) {
              srchPos1        = files[i].indexOf(srchvalue1);
              srchPos2        = files[i].indexOf(srchvalue2);
              if ((srchPos1 != -1) && (srchPos2 != -1)){
                     zipFileTag = files[i].substring((srchPos1 + srchvalue1.length()), srchPos2);
              }
         }
         BufferedInputStream origin = null;
         String zipFileName = cfgObj.zipFileName + formatter.format(new Date()) + zipFileTag.trim() +".zip";
         FileOutputStream dest      = new FileOutputStream(cfgObj.zipToTransferDirectory + zipFileName);
         ZipOutputStream out        = new ZipOutputStream(new BufferedOutputStream(dest));
         System.out.println("Building Zip ->" + cfgObj.zipToTransferDirectory + zipFileName);

         //out.setMethod(ZipOutputStream.DEFLATED);
         byte data[] = new byte[BUFFER];

         for (int i=0; i<files.length; i++) {
            System.out.println("Adding: "+files[i]);
            //cfgObj.write("Process Name(BuildZipSet)- Adding: " + files[i]);
            FileInputStream fi = new FileInputStream(cfgObj.workDirectory + files[i]);
            origin             = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry     = new ZipEntry(files[i]);

            if (files[i].indexOf(".csv")>-1){
                DBLog.updateDeliveryRecord(files[i],zipFileName);
            }

            out.putNextEntry(entry);
            int count;
            while((count = origin.read(data, 0, BUFFER)) != -1) {
               out.write(data, 0, count);
            }
            origin.close();
            PrepareFiles.BuildFileSet(cfgObj.workDirectory + files[i], cfgObj.tempDirectory);
         }
         out.close();
         // reset contents of the command file since file cannot be deleted and is lock by another process
         dest = new FileOutputStream(cfgObj.workDirectory + cfgObj.notifyEmailCommandFileName);
         dest.close();

         // reset contents of the command file since file cannot be deleted and is lock by another process
         dest = new FileOutputStream(cfgObj.workDirectory + cfgObj.notifyEmailBodyFileName);
         dest.close();
         } catch (Exception ex) {
             System.out.print("Process Name(BuildZipSet)- " + ex.getClass() + " " + ex.getMessage());
      }
   }

   public static void ZipSubscriptionDelivery(){
      try {
         File f               = new File(cfgObj.pdfWorkDirectory); // get a list of files from current directory
         String files[]       = f.list();
         DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'X'");

         // these variables are needed to get a unique file name based from the input
         String srchvalue1    = "X", srchvalue2 = ".", zipFileTag ="";
         int srchPos1         = 0,   srchPos2 = 0,     zipFileNumber = 0;
         //create a unique file name based from the input filename of the csv file
         for (int i=0; i<files.length; i++) {
              srchPos1 = files[i].indexOf(srchvalue1);
              srchPos2 = files[i].indexOf(srchvalue2);
              if ((srchPos1 != -1) && (srchPos2 != -1)){
                     zipFileTag = files[i].substring((srchPos1 + srchvalue1.length()), srchPos2);
              }
         }
         BufferedInputStream origin = null;
         String zipFileName = cfgObj.zipSubsFileName + formatter.format(new Date()) + zipFileTag.trim() +".zip";
         FileOutputStream dest      = new FileOutputStream(cfgObj.pdfTransferDirectory + zipFileName);
         ZipOutputStream out        = new ZipOutputStream(new BufferedOutputStream(dest));
         System.out.println("Building Zip ->" + cfgObj.pdfTransferDirectory + zipFileName);

         //out.setMethod(ZipOutputStream.DEFLATED);
         byte data[] = new byte[BUFFER];

         for (int i=0; i<files.length; i++) {
            System.out.println("Adding: "+files[i]);

            if (files[i].indexOf(".csv")>-1){
                DBLog.updateDeliveryRecord(files[i],zipFileName);
            }


            FileInputStream fi = new FileInputStream(cfgObj.pdfWorkDirectory + files[i]);
            origin             = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry     = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while((count = origin.read(data, 0, BUFFER)) != -1) {
               out.write(data, 0, count);
            }
            origin.close();
            PrepareFiles.BuildFileSet(cfgObj.pdfWorkDirectory + files[i], cfgObj.pdfTempDirectory);
         }
         out.close();
         // reset contents of the command file since file cannot be deleted and is lock by another process
         dest = new FileOutputStream(cfgObj.pdfWorkDirectory + cfgObj.pdfEmailCommandFileName);
         dest.close();

         // reset contents of the command file since file cannot be deleted and is lock by another process
         dest = new FileOutputStream(cfgObj.pdfWorkDirectory + cfgObj.pdfEmailBodyFileName);
         dest.close();

         } catch (Exception ex) {
             System.out.print("Process Name(ZipSubscriptionDelivery)- " + ex.getClass() + " " + ex.getMessage());
      }
   }

   public static void ZipAdhocDelivery(){
      try {
         // get a list of files from current directory
         File f               = new File(cfgObj.pdfAdWorkDirectory);
         String files[]       = f.list();
         DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'X'");

         // these variables are needed to get a unique file name based from the input
         String srchvalue1 = "X", srchvalue2 = ".", zipFileTag    ="";
         int srchPos1      = 0,   srchPos2   = 0,   zipFileNumber = 0;
         //create a unique file name based from the input filename of the csv file
         for (int i=0; i<files.length; i++) {
              srchPos1 = files[i].indexOf(srchvalue1);
              srchPos2 = files[i].indexOf(srchvalue2);
              if ((srchPos1 != -1) && (srchPos2 != -1)){
                     zipFileTag = files[i].substring((srchPos1 + srchvalue1.length()), srchPos2);
              }
         }
         BufferedInputStream origin = null;
         String zipFileName = cfgObj.zipAdhocFileName + formatter.format(new Date()) + zipFileTag.trim() +".zip";
         FileOutputStream dest = new FileOutputStream(cfgObj.pdfAdTransferDirectory + zipFileName);
         ZipOutputStream out   = new ZipOutputStream(new BufferedOutputStream(dest));
         System.out.println("Building Zip ->" + cfgObj.pdfAdTransferDirectory + zipFileName);

         //out.setMethod(ZipOutputStream.DEFLATED);
         byte data[] = new byte[BUFFER];

         for (int i=0; i<files.length; i++) {
            System.out.println("Adding: "+files[i]);

            if (files[i].indexOf(".csv")>-1){
                DBLog.updateDeliveryRecord(files[i],zipFileName);
            }

            FileInputStream fi = new FileInputStream(cfgObj.pdfAdWorkDirectory + files[i]);
            origin             = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry     = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while((count = origin.read(data, 0, BUFFER)) != -1) {
               out.write(data, 0, count);
            }
            origin.close();
            PrepareFiles.BuildFileSet(cfgObj.pdfAdWorkDirectory + files[i], cfgObj.pdfAdTempDirectory);
         }
         out.close();
         // reset contents of the command file since file cannot be deleted and is lock by another process
         dest = new FileOutputStream(cfgObj.pdfAdWorkDirectory + cfgObj.pdfAdEmailCommandFileName);
         dest.close();

         // reset contents of the command file since file cannot be deleted and is lock by another process
         dest = new FileOutputStream(cfgObj.pdfAdWorkDirectory + cfgObj.pdfAdEmailBodyFileName);
         dest.close();

         } catch (Exception ex) {
             System.out.print("Process Name(ZipAdhocDelivery)- " + ex.getClass() + " " + ex.getMessage());
      }
   }

   public static void ZipReprintDelivery(String mailMethod){
      try {
         // get a list of files from current directory
         File f               = new File(cfgObj.reprintWorkDirectory);
         String files[]       = f.list();
         DateFormat formatter = new SimpleDateFormat("ddMMyyHHmm");

         // these variables are needed to get a unique file name based from the input
         String srchvalue1 = "_", srchvalue2 = ".", zipFileTag    ="";
         int srchPos1      = 0,   srchPos2   = 0,   zipFileNumber = 0;
         //create a unique file name based from the input filename of the csv file
         for (int i=0; i<files.length; i++) {
              srchPos1 = files[i].indexOf(srchvalue1);
              srchPos2 = files[i].indexOf(srchvalue2);
              if ((srchPos1 != -1) && (srchPos2 != -1)){
                     zipFileTag = files[i].substring((srchPos1 + srchvalue1.length()), srchPos2);
              }
         }
         BufferedInputStream origin = null;
         String prepend = "NORM";
         if (mailMethod.equals(BillReprintDeliver.COURIER)){
           prepend = "COUR";
         }
         String zipFileName = prepend + formatter.format(new Date()) + zipFileTag.trim() +".zip";
         FileOutputStream dest = new FileOutputStream(cfgObj.reprintTransferDirectory + zipFileName);
         ZipOutputStream out   = new ZipOutputStream(new BufferedOutputStream(dest));
         System.out.println("Building Zip ->" + cfgObj.reprintTransferDirectory + zipFileName);

         //out.setMethod(ZipOutputStream.DEFLATED);
         byte data[] = new byte[BUFFER];

         for (int i=0; i<files.length; i++) {
            System.out.println("Adding: "+files[i]);

            if (files[i].indexOf(".csv")>-1){
                DBLog.updateReprintRecord(files[i],zipFileName);
            }

            FileInputStream fi = new FileInputStream(cfgObj.reprintWorkDirectory + files[i]);
            origin             = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry     = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while((count = origin.read(data, 0, BUFFER)) != -1) {
               out.write(data, 0, count);
            }
            origin.close();
            PrepareFiles.BuildFileSet(cfgObj.reprintWorkDirectory + files[i], cfgObj.reprintTempDirectory);
         }
         out.close();

         } catch (Exception ex) {
             System.out.print("Process Name(ZipReprintDelivery)- " + ex.getClass() + " " + ex.getMessage());
      }
   }
}

